//
//  STCirculationView.swift
//  iPhone
//
//  Created by Toj on 6/15/22.
//

import UIKit

protocol STCirculationViewDelegate: NSObjectProtocol {
    func circulationView(view: STCirculationView, didSelectedModel: FloatADModel)
    func circulationViewDidTapClose(view: STCirculationView)
}

extension STCirculationViewDelegate {
    func circulationView(view: STCirculationView, didSelectedModel: FloatADModel) { }
}

open class STCirculationView: UIView {
    
    weak var delegage: STCirculationViewDelegate?
    
    public var circulationSize: CGSize = .zero {
        didSet {
            collectionLayout.itemSize = circulationSize
        }
    }
    
    public var datas: [FloatADModel]? {
        didSet {
            setupData()
        }
    }
    
    private var showDatas: [FloatADModel]?
    private func setupData() {
        setDataTimes()
        
        var showObjects = datas
        guard let data = datas, data.count > 1 else {
            showDatas = showObjects
            collectionView.reloadData()
            return
        }
        // 首尾添加视觉图
        if let lastItem = data.last {
            showObjects?.insert(lastItem, at: 0)
            showDatas = showObjects
        }
        collectionView.reloadData()
        
        startScrollTimer()
        
        setPageControl(datas?.count ?? 0)
    }
    
    private func setDataTimes() {
        guard let model = datas?.first else { return }
        
        closeButton.isHidden = !model.supportClose
        countDownLabel.isHidden = !(model.closingTime > 0)
        countDown = model.closingTime
        if countDownLabel.isHidden { return }
        
        let txt = "\(countDown)S"
        countDownLabel.text = txt
        
        let offset = closeButton.isHidden ? 4.5 : (29.5)
        let width = txt.cm_stringWidth(font: countDownLabel.font, maxHeight: 1) + 6
        countDownLabel.snp.remakeConstraints { (make) in
            make.centerY.equalTo(closeButton)
            make.right.equalTo(snp.right).offset(-offset)
            make.width.equalTo(width)
            make.height.equalTo(16)
        }
        
        startCountDownTimer()
    }
    
    private func setPageControl(_ itemCount: Int){
        pageControl.isHidden = itemCount <= 1
        if pageControl.isHidden { return }
        
        pageControl.numberOfPages = itemCount
        pageControl.currentPage = 0
        
        let size = pageControl.sizeForNumberOfPages
        pageControl.snp.remakeConstraints { (make) in
            make.right.equalTo(snp.right).offset(-8)
            make.bottom.equalTo(snp.bottom).offset(-8)
            make.height.equalTo(size.height)
            make.width.equalTo(size.width)
        }
    }
    
    public var isDragging = true {
        didSet {
            collectionView.isScrollEnabled = isDragging
        }
    }
    public var scrollTimeInterval = 2.0
    
    private var scrollIndex = 1
    
    private var scrollTimer: Timer?
    
    private var countDown = 0
    private var countDownTimer: Timer?
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(collectionView)
        addSubview(countDownLabel)
        addSubview(closeButton)
        addSubview(pageControl)
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        collectionView.snp.remakeConstraints { (make) in
            make.left.bottom.right.equalTo(self)
            make.height.equalTo(circulationSize.height)
        }
        
        closeButton.snp.remakeConstraints { (make) in
            make.top.right.equalTo(self)
            make.width.height.equalTo(25)
        }
    }
    
    public required  init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func startCountDownTimer(){
        if countDownTimer == nil {
            let timer = Timer.st_scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCountDownCallBack), userInfo: nil, repeats: true)
            countDownTimer = timer
        }
    }
    
    public func startScrollTimer(){
        if scrollTimer == nil {
            let timer = Timer.st_scheduledTimer(timeInterval: scrollTimeInterval, target: self, selector: #selector(timerScrollCallBack), userInfo: nil, repeats: true)
            scrollTimer = timer
        }
    }
    
    public func stopAllTimer(){
        stopScrollTimer()
        
        stopCountDownTimer()
    }
    
    private func stopCountDownTimer(){
        countDownTimer?.invalidate()
        countDownTimer = nil
    }
    
    private func stopScrollTimer(){
        scrollTimer?.invalidate()
        scrollTimer = nil
    }
    
    @objc private func timerCountDownCallBack() {
        countDown -= 1
        // print("timerCountDown: \(countDown)")
        countDownLabel.text = "\(countDown)S"
        if countDown == 0 {
            didTapClose()
        }
    }
    
    @objc private func timerScrollCallBack() {
        
        guard let datas = showDatas, datas.count > 1 else {
            stopScrollTimer()
            return
        }
        
        scrollIndex = scrollIndex + 1
        if scrollIndex <= datas.count - 1 {
            // print("timerScrollCallBack: 0 - \(scrollIndex)")
            collectionView.scrollToItem(at: IndexPath(row: scrollIndex, section: 0), at: .left, animated: true)
            pageControl.currentPage = scrollIndex - 1
            return
        }
        collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: UICollectionView.ScrollPosition.left, animated: false)
        scrollIndex = 1
        // print("timerScrollCallBack: 1 - \(scrollIndex)")
        pageControl.currentPage = scrollIndex - 1
        collectionView.scrollToItem(at: IndexPath(row: scrollIndex, section: 0), at: .right, animated: true)
    }
    
    @objc func didTapClose() {
        stopCountDownTimer()
        isHidden = true
        delegage?.circulationViewDidTapClose(view: self)
    }
    
    private lazy var collectionLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
        view.isPagingEnabled = true
        view.showsHorizontalScrollIndicator = false
        view.scrollsToTop = false
        view.dataSource = self
        view.delegate = self
        view.backgroundColor = .clear
        
        view.register(STCirculationCell.self, forCellWithReuseIdentifier: STCirculationCell.cell_identifier)
        return view
    }()
    
    private lazy var countDownLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor(hex: 0x666666)
        view.backgroundColor = UIColor(hex: 0xFFFFFF)
        view.font = UIFont.systemFont(ofSize: 12)
        view.layer.borderWidth = 1
        view.layer.borderColor = view.textColor.cgColor
        view.layer.cornerRadius = 8
        view.layer.masksToBounds = true
        view.textAlignment = .center
        return view
    }()
    
    private lazy var closeButton: UIButton = {
        let view = UIButton()
        view.setImage(UIImage(named: "circulation_ad_ic_close"), for: .normal)
        view.addTarget(self, action: #selector(didTapClose), for: .touchUpInside)
        return view
    }()
    
    private lazy var pageControl: STPageControl = {
        let view = STPageControl()
        view.backgroundColor = UIColor.clear
        view.isEnabled = false
        view.currentPage = 0
        view.currentPageIndicatorColor = .blue
        view.pageIndicatorColor = .red
        view.currentPageIndicatorColor = UIColor(hex: 0x0087EB)
        view.pageIndicatorColor = .white.tt_alpha(0.5)
        return view
    }()
    
    deinit {
        // print("-->toj: deinit STCirculationView")
        stopAllTimer()
    }
}

extension STCirculationView: UICollectionViewDataSource {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return showDatas?.count ?? 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = showDatas?[indexPath.row]
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifierClass: STCirculationCell.self, for: indexPath)
        cell.model = model
        
        return cell
    }
}

extension STCirculationView: UICollectionViewDelegate {
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath, convertTo: STCirculationCell.self)
        guard let model = cell?.model else { return }
        print(model.materials)
        
        delegage?.circulationView(view: self, didSelectedModel: model)
    }
}
